//
//  KWLScanCodeLoginViewController.m
//  KWNLaywerClient
//
//  Created by 孔六五 on 14/12/14.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "KWLScanCodeLoginViewController.h"
#import "KFLLoginproRequest.h"
#import "KWLLoginViewController.h"
#import "KFLWebLoginOutRequest.h"
#import "MLBlackTransition.h"

#undef  FrameWithWebLogin
#define FrameWithWebLogin  CGRectMake((self.view.frame.size.width - 163)/2, view_title.frame.origin.y + view_title.frame.size.height + Iphone5_size(40,20), 163, 86)

#undef  FrameWithWebLoginSuccesOrFailed
#define FrameWithWebLoginSuccesOrFailed  CGRectMake((self.view.frame.size.width - 163)/2, view_title.frame.origin.y + view_title.frame.size.height + Iphone5_size(80,50), 163, 86)


@interface KWLScanCodeLoginViewController ()

@property (nonatomic,strong) UIButton *button_webLogin;
@property (nonatomic,strong) UIButton *button_webLoginCancel;
@property (nonatomic,strong) UIButton *button_webLoginOut;
@property (nonatomic,strong) UIButton *button_webLoginBack;

@property (nonatomic,strong) UIImageView *imageview_WLImageView;
@property (nonatomic,strong) UIImageView *imageview_WLExplainImageView;
@property (nonatomic, strong) UIView *view_title;
@property (nonatomic,strong) NSString *codeStr;
@end

@implementation KWLScanCodeLoginViewController
@synthesize button_webLogin;
@synthesize button_webLoginCancel;
@synthesize button_webLoginOut;
@synthesize imageview_WLExplainImageView;
@synthesize imageview_WLImageView;
@synthesize view_title;
@synthesize button_webLoginBack;
@synthesize codeStr;


- (id)initWithCodeStr:(NSString *)code;
{
    self = [super init];
    if(self)
    {
        self.codeStr = code;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view setBackgroundColor:RGB(235, 235, 240)];
    
    view_title = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44 + IOS7_SIZE)];
    view_title.backgroundColor = RGB(91, 165, 229);
    [self.view addSubview:view_title];

    ///手势
    if(IOS7_VERSION){
        [self.navigationController enabledMLBlackTransition:NO];
    }
    else{
        [self.navigationController_MI setCanDragBack:NO];
    }
    
    UILabel *label_title = [[UILabel alloc] initWithFrame:CGRectMake(view_title.frame.origin.x,IOS7_SIZE + 5,view_title.frame.size.width,35)];
    label_title.backgroundColor = [UIColor clearColor];
    label_title.textColor = RGB(63, 119, 167);
    label_title.textAlignment = NSTextAlignmentCenter;
    label_title.font = FontOfHelveticaBold(16);
    [self.view addSubview:label_title];
    label_title.text = @"二维码登录";

    button_webLoginBack = [UIButton buttonWithType:UIButtonTypeCustom];
    button_webLoginBack.frame = CGRectMake(0, IOS7_SIZE, 60, 45);
    [button_webLoginBack setImage:[UIImage imageFileName:@"button_back.png"] forState:UIControlStateNormal];
    //button_menu.tag = KWNDetailViewButtonTag_back;
    [button_webLoginBack addTarget:self action:@selector(ClickButton_webLoginBack:) forControlEvents:UIControlEventTouchUpInside];
    button_webLoginBack.hidden = YES;
    [self.view addSubview:button_webLoginBack];

    imageview_WLImageView = [[UIImageView alloc] initWithFrame:FrameWithWebLogin];
    imageview_WLImageView.image = [UIImage imageFileName:@"imageview_WLImage.png"];
    [self.view addSubview:imageview_WLImageView];
    
    imageview_WLExplainImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 209)/2, imageview_WLImageView.frame.origin.y + imageview_WLImageView.frame.size.height +  Iphone5_size(60,40), 209, 68)];
    imageview_WLExplainImageView.image = [UIImage imageFileName:@"imageview_WLExplainImage1.png"];
    [self.view addSubview:imageview_WLExplainImageView];
    
    button_webLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_webLogin setBackgroundImage:[UIImage imageFileName:@"button_webLogin.png"] forState:UIControlStateNormal];
    [button_webLogin addTarget:self action:@selector(ClickButton_webLogin:) forControlEvents:UIControlEventTouchUpInside];
    button_webLogin.frame = CGRectMake((self.view.frame.size.width - 278)/2, self.view.frame.size.height - 88 - 30 - Iphone5_size(10,20), 278, 44);
    [self.view addSubview:button_webLogin];

    button_webLoginCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_webLoginCancel setBackgroundImage:[UIImage imageFileName:@"button_webLoginCancel.png"] forState:UIControlStateNormal];
    [button_webLoginCancel addTarget:self action:@selector(ClickButton_webLoginCancel:) forControlEvents:UIControlEventTouchUpInside];
    button_webLoginCancel.frame = CGRectMake((self.view.frame.size.width - 278)/2, self.view.frame.size.height - 44 - 15 - Iphone5_size(10,20), 278, 44);
    [self.view addSubview:button_webLoginCancel];
    
    button_webLoginOut = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_webLoginOut setBackgroundImage:[UIImage imageFileName:@"button_webLoginOut.png"] forState:UIControlStateNormal];
    [button_webLoginOut addTarget:self action:@selector(ClickButton_webLoginOut:) forControlEvents:UIControlEventTouchUpInside];
    button_webLoginOut.frame = CGRectMake((self.view.frame.size.width - 278)/2, self.view.frame.size.height - 44 - 15 - Iphone5_size(10,20), 278, 44);
    [self.view addSubview:button_webLoginOut];
    button_webLoginOut.hidden = YES;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//返回
- (void)ClickButton_webLoginBack:(id)sender
{
    [self popViewController];
}

//授权网页登录
- (void)ClickButton_webLogin:(id)sender
{
    NSDictionary *dic = [self dicFromCode];
    if (dic) {
        NSString *content = [dic objectForKey:@"content"];
        if (content) {
            if([content isEqualToString:@"1"])
            {
// CS 快法务 KLW 2014-12-24
//                [UIUtils view_showProgressHUD:@"加载中" inView:self.view withType:0];
//                
                [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
// CE 快法务 KLW 2014-12-24
                KFLLoginproRequest *isqrcode = [[KFLLoginproRequest alloc] initRequest];
                isqrcode.code = [dic objectForKey:@"code"];
                [isqrcode startToRequestWithBlock:^(NSInteger stateCode, NSMutableArray *result) {
// DS 快法务 KLW 2014-12-24
//                    [UIUtils view_hideProgressHUDinView:self.view];
//                    
// DE 快法务 KLW 2014-12-24
                    switch (stateCode) {
                        case 10000:
                        {
// AS 快法务 KLW 2014-12-24
                            [SVProgressHUD dismiss];
// AE 快法务 KLW 2014-12-24
                            [self webLoginSucceed];
                        }
                            break;
                        case 10003:
                        {
// AS 快法务 KLW 2014-12-24
                            [SVProgressHUD dismiss];
// AE 快法务 KLW 2014-12-24
                            [self scanCodeToWebLoginTokenIsFailure];
                        }
                            break;
                        default:
                        {
                            NSString *string_msg  = result[0];
// CS 快法务 KLW 2014-12-24
//                            [UIUtils view_showProgressHUD:string_msg inView:self.view withTime:1.5f];
//                            
                            [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
// CE 快法务 KLW 2014-12-24
                            double delayInSeconds = 1.5;
                            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                                [self webLoginFailed];
                            });
                        }
                            break;
                    }
                }];
                
            }
            
        }
    }

}

//取消操作
- (void)ClickButton_webLoginCancel:(id)sender
{
    [self popViewController];
}

//取消登录
- (void)ClickButton_webLoginOut:(id)sender
{
// CS 快法务 KLW 2014-12-24
//    [UIUtils view_showProgressHUD:@"加载中" inView:self.view withType:0];
//    
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeClear];
// CE 快法务 KLW 2014-12-24
    KFLWebLoginOutRequest *webloginout = [[KFLWebLoginOutRequest alloc] initRequest];
    [webloginout startToRequestWithBlock:^(NSInteger stateCode, NSMutableArray *result) {
// DS 快法务 KLW 2014-12-24
//        [UIUtils view_hideProgressHUDinView:self.view];
//        
// DE 快法务 KLW 2014-12-24
        switch (stateCode) {
            case 10000:
            {
// AS 快法务 KLW 2014-12-24
                [SVProgressHUD dismiss];
// AE 快法务 KLW 2014-12-24
                [self popViewControllerToRootView];
            }
                break;
            case 10003:
            {
// AS 快法务 KLW 2014-12-24
                [SVProgressHUD dismiss];
// AE 快法务 KLW 2014-12-24
                [self scanCodeToWebLoginTokenIsFailure];
            }
                break;
            default:
            {
                NSString *string_msg  = result[0];
// CS 快法务 KLW 2014-12-24
//                [UIUtils view_showProgressHUD:string_msg inView:self.view withTime:1.5f];
//                
                [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
// CE 快法务 KLW 2014-12-24
            }
                break;
        }
    }];

}

//网页登录成功修改界面
- (void)webLoginSucceed
{
    imageview_WLImageView.frame = FrameWithWebLoginSuccesOrFailed;
    imageview_WLExplainImageView.image = [UIImage imageFileName:@"imageview_WLExplainImage2.png"];
    imageview_WLExplainImageView.frame = CGRectMake((self.view.frame.size.width - 187)/2, imageview_WLImageView.frame.origin.y + imageview_WLImageView.frame.size.height + Iphone5_size(80, 60), 187, 20);
    button_webLogin.hidden = YES;
    button_webLoginCancel.hidden = YES;
    button_webLoginOut.hidden = NO;
}

//网页登录失败修改界面
- (void)webLoginFailed
{
    button_webLoginBack.hidden = NO;
    imageview_WLImageView.frame = FrameWithWebLoginSuccesOrFailed;
    imageview_WLExplainImageView.image = [UIImage imageFileName:@"imageview_WLExplainImage3.png"];
    imageview_WLExplainImageView.frame = CGRectMake((self.view.frame.size.width - 249)/2, imageview_WLImageView.frame.origin.y + imageview_WLImageView.frame.size.height + Iphone5_size(80, 50), 249, 51);
    button_webLogin.hidden = YES;
    button_webLoginCancel.hidden = YES;
    button_webLoginOut.hidden = YES;
    
    ///手势
    if(IOS7_VERSION){
        [self.navigationController enabledMLBlackTransition:YES];
    }
    else{
        [self.navigationController_MI setCanDragBack:YES];
    }
}

- (NSDictionary *)dicFromCode
{
    NSData* data_content = [codeStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *codeDic = [NSJSONSerialization JSONObjectWithData:data_content options:NSJSONReadingMutableLeaves error:&error];
    if (!error) {
        return codeDic;
    }
    return nil;
}

#pragma mark - 账号被替换下线提示 -
- (void)scanCodeToWebLoginTokenIsFailure{
    UIAlertView *alter_login;
    if(IOS8_VERSION){
        alter_login = [[UIAlertView alloc] initWithTitle:@"您的来问律师账号已在其它地方登录，请您重新登录此设备。如果不是您的操作，您的密码可能已泄露，请及时更改密码，或联系快问律师客服邮箱laiwenlvshi@kuaifawu.com。" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    else{
        alter_login = [[UIAlertView alloc] initWithTitle:nil message:@"您的来问律师账号已在其它地方登录，请您重新登录此设备。如果不是您的操作，您的密码可能已泄露，请及时更改密码，或联系快问律师客服邮箱laiwenlvshi@kuaifawu.com。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    alter_login.tag = 10003;
    [alter_login show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (alertView.tag) {
        case 10003:{
            KWLLoginViewController *login = [[KWLLoginViewController alloc] initWithTag:6];
            [self pushViewController:login];
        }break;
            
        default:
            break;
    }
}

@end
